<template>
  <div style="position: relative;border-radius:5px;width: 380px;display: flex;justify-content: space-between;">
    <div style="width: 49%;">
        <el-upload v-bind="props" v-model:file-list="value"
                   :class="props.isMemberUse?'upload-demo1':'upload-demo'"
                   drag
                   action="https://www.caixue8.cn/api/upload/file"
                   multiple
                   :accept="props.upload_type"
                   :limit="props.maxlength"
                   :headers="headers"
                   :data="data"
                   :on-success="onSuccess"
                   :on-error="onError"
                   :before-upload="beforeUpload"
                   :on-exceed="handleExceed"
        >
          <div class="color">电脑上传</div>
          <img src="https://www.caixue8.cn/uploads/file.png" class="pos-image" />
          <div class="el-upload__text">
            {{props.title}}
          </div>

        </el-upload>
    </div>
    <div :class="props.isMemberUse?'shouji1':'shouji'" @click="saomasj('file')" style="height:102px;display: flex;justify-items: center;align-items: center;justify-content: center;">
      <div>
        <div style="height: 20px;" class="color">手机上传</div>
        <div class="img-d" style="margin-top: 6px">
          <img src="@/assets/images/qrcode.png" class="pos-image">
        </div>
      </div>
    </div>
  </div>

  <el-dialog
      v-model="dialogVisibleVip"
      center
      title="扫描二维码，在手机快速上传"
      width="500"
      :before-close="handleClose"
  >

    <div style=" display: flex;justify-content: center;">
      <img :src="qrcode_url" alt="Base64 Image"/>
    </div>
    <div style="text-align: center;color: red">建议使用微信扫码</div>
    <div @click="handleClose" class="success">已上传完成</div>
  </el-dialog>

</template>

<script setup lang="ts">
import type { InputProps,UploadProps, UploadUserFile } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import {useUserStore} from "~/stores/user";
import {computed, ref} from "vue";
import {getVersion} from "~/utils/env";
import {scanUploadFile, scanUploadQrcode} from "~/api/chat";
import feedback from "~/utils/feedback";
const userStore = useUserStore()
interface Props extends Partial<InputProps> {}
const props = withDefaults(defineProps<Props>(), {
  showWordLimit: true,
  isEnable:true,
  isMemberUse:false
})
const dialogVisibleVip = ref(false)

const qrcode_url = ref('')


const emit = defineEmits<{
  (event: 'update:modelValue', value: any): void
}>()
const value = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    console.log(value)
    let file = value[0].name
    emit('update:modelValue', value)
  }
})

const saData = ref([])

const headers = computed(() => ({
  token: userStore.token,
  version: getVersion()
}))
const data = computed(() => ({
  type: 'docs',
  key:'kimi-chatdoc'
}))
console.log(headers)
const onSuccess = (e) => {
  emit('fileStatus', 1)
  if(e.code == 0){
    ElMessage({
      showClose: true,
      message: e.msg,
      type: 'error',
    })
    if (value.value && value.value.length > 0) {
      console.log('Filtering files...')
      value.value = value.value.filter(file => {
        console.log('File object:', file)
        console.log('File response:', file.response)
        return file.response.code !== 0
      })
    }
  }
}


const successWa = () => {
  stopPolling();
  handleClose()

}


const handleClose = () => {
  stopPolling();
  dialogVisibleVip.value = false
}

const handleExceed = () => {
  ElMessage({
    showClose: true,
    message: '上传的文件数量不能超过 ' + props.maxlength + '个',
    type: 'error',
  })
}


const arocde_data = reactive({
  setIntervalFlag: null
})


const saomasj = async (key) => {
  lx_num.value = 1
  let other_id = window.localStorage.getItem('other_id')
  const data = await scanUploadQrcode({key: key,model_id:other_id})
  if(data){
    dialogVisibleVip.value = true
    qrcode_url.value = data.base64ImageHTML
    saData.value = data
    startPolling()
  }else{
    feedback.msgError(data.msg)
  }
}


const lx_num = ref(0)
const lunxun = async() => {
  lx_num.value++
  console.log(lx_num.value)
  const data = await scanUploadFile({tokens: saData.value.tokens})
  if(data.data.length > 0) {
    stopPolling();
    feedback.msgSuccess('上传成功')
    value.value = data.data
  }else{
    if(lx_num.value >= 20){
      dialogVisibleVip.value = false
      if(data.scan_status == 0){
        feedback.msgError('二维码已过期')
        stopPolling();
      }
    }else{
      if(data.scan_status == 1){
        lx_num.value = 21
        feedback.msgSuccess('扫码成功')
        dialogVisibleVip.value = false
      }
    }
  }
}





const startPolling = () => {
  // 设置轮询间隔时间，例如5秒
  const interval = 1000;
  // 使用setInterval发起请求
  arocde_data.setIntervalFlag = setInterval(() => {
    lunxun()
  }, interval);
}

const stopPolling = () => {
  // 清除定时器
  if (arocde_data.setIntervalFlag) {
    clearInterval(arocde_data.setIntervalFlag);
    arocde_data.setIntervalFlag = null;
  }
}

const onError = (e) => {
  ElMessage({
    showClose: true,
    message: e.msg,
    type: 'error',
  })
  emit('fileStatus', 1)
}

const beforeUpload = (file) => {
  emit('fileStatus', 0)
  const isLt500KB = file.size / 1024 / 1024 < props.maxupload;
  console.log(file.size / 1024 / 1024,props)
  if (!isLt500KB) {
    ElMessage({
      showClose: true,
      message: '上传的文件大小不能超过 ' + props.maxupload + 'M',
      type: 'error',
    })
  }
  return isLt500KB;
}

</script>
<style lang="scss" scoped>
.pos-image {
  width: 40px!important;
  height: 40px!important;
  left:0;
  right: 0;
  text-align: center;
  margin: auto;
  top:50%
}
.upload-demo1{
  :deep(.el-upload-dragger) {
    border:0.5px solid #784c2c;
    padding: 10px;
  }
}
.upload-demo{
  :deep(.el-upload-dragger) {
    padding: 10px;
  }
}
.shouji {
  width: 50%;
  line-height: 22px;
  text-align: center;
  height: 60px;
  border: 1px dashed #dcdfe6;
}
.shouji1 {
  width: 50%;
  line-height: 22px;
  text-align: center;
  height: 62px;
  border: 1px solid #784c2c;
  border-radius: 5px;
}
.img-d {
  text-align: center;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.success {
  text-align: center;
  background: #ffb100;
  color: white;
  border-radius: 40px;
  cursor: pointer;
}

.color {
  color: #9e9e9e;
}
</style>
